package hot100.logos51To60;

import java.util.ArrayList;
import java.util.List;

/**
 * @author logos
 * date 2025/7/15 12:07
 * @version v1.0
 * @Package hot100.logos51To60
 */
public class logos52 {


    /**
     * 52. 腐烂的橘子
     * https://leetcode.cn/problems/rotting-oranges/?envType=study-plan-v2&envId=top-100-liked
     */

    class Solution {
        private int[][] dirs = new int[][] { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };

        public int orangesRotting(int[][] grid) {
            int n = grid.length;
            int m = grid[0].length;
            int fresh = 0;
            List<int[]> que = new ArrayList<>();
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < m; j++) {
                    if (grid[i][j] == 1) {
                        fresh++;
                    } else if (grid[i][j] == 2) {
                        que.add(new int[] { i, j });
                    }
                }
            }
            int ans = 0;
            while (fresh > 0 && !que.isEmpty()) {
                ans++;
                List<int[]> tmp = que;
                que = new ArrayList<>();
                for (int[] pos : tmp) {
                    for (int[] dir : dirs) {
                        int x = pos[0] + dir[0];
                        int y = pos[1] + dir[1];
                        if (x >= 0 && x < n && y >= 0 && y < m && grid[x][y] == 1) {
                            fresh--;
                            grid[x][y] = 2;
                            que.add(new int[] { x, y });
                        }
                    }
                }
            }
            return fresh > 0 ? -1 : ans;
        }
    }
}
